<template>
  <div class="personalSettingAuthentication_container pr-1 pl-1">
    <!-- 四种认证方式 -->
		<div class="personalSettingAuthentication_container_card br-16 padding-1">
			<div class="container_card_phoneNum" v-if="type == 1">
				<div class="container_card_title mb-0">{{ $t("选择国家/地区") }}</div>
				<div class="container_card_select mb-1" @click="goNationalIndexBar">
					<div class="container_card_select_value">{{ phoneNum.nation }}</div>
					<img src="@/image/aiQuantization/indexTop/arrow.png" alt="">
				</div>
				<div class="container_card_title mb-0">{{ $t("手机号码") }}</div>
				<div class="container_card_input mb-1">
					<div class="container_card_select_icon">
						<span class="mr-0">{{ phoneNum.areaCode }}</span>
						<img :src="phoneNum.flag" alt="">
					</div>
					<input type="text" v-model="phoneNum.phoneNumber" :placeholder="$t('请输入手机号码')">
				</div>
				<div class="container_card_content mb-1">
					<p class="mb-0">{{ $t("请在输入框中填写您的手机号码,我们将通过这个号码验证您的身份。") }}</p>
					<p>{{ $t("我们重视您的隐私，提供的手机号码将严格保密，仅用于认证目的。") }}</p>
				</div>
			</div>
			<div class="container_card_livingBills" v-else-if="type == 3">
				<div class="container_card_title mb-0">{{ $t("我们接受") }}</div>
				<div class="container_card_icon_content padding-0 mb-1 pr-1 pl-1 br-8">
					<div class="container_card_icon_content_item" v-for="(item,index) in livingBills_icon_list" :key="index">
						<div class="item_icon_box">
							<div class="item_icon"></div>
						</div>
						<div>{{ item }}</div>
					</div>
				</div>
				<div class="container_card_title mb-0">{{ $t("我们不接受") }}</div>
				<div class="container_card_icon_content padding-0 mb-1 pr-1 pl-1 br-8">
						<div class="container_card_icon_content_item">
							{{ livingBills_list[0] }}
						</div>
				</div>
				<div class="container_card_icon_content padding-0 mb-1 pr-1 pl-1 br-8">
					<div class="upload_box" @click.stop="uploadClick">
						<div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
							<van-circle
									v-model="uploadProgress"
									:stroke-width="60"
									layer-color="#2e2e2e"
									:rate="uploadProgress"
									:speed="100"
									:text="uploadProgress + '%'"
							/>
						</div>
						<img v-if="uploadedImage" :src="uploadedImage" class="preview-image" alt="">
						<van-icon 
								v-if="uploadedImage"
								name="clear" 
								class="delete-icon"
								@click.stop="handleDelete"
						/>
						<template v-else-if="uploading">
							<div class="uploading_text">{{ $t("上传中...") }}</div>
						</template>
						<template v-else>
								<img src="@/image/personalCenter/setting/realName/carma.png" class="mb-0" alt="">
								<div class="upload_box_title">{{ $t("点击上传照片") }}</div>
						</template>
					</div>
				</div>
			</div>
			<div class="container_card_identity" v-else-if="type == 2">
				<p>{{ $t("请手持以下文档自拍") }}</p>
				<p>{{ $t("拍一张照片，满足以下条件:") }}</p>
				<p class="mb-1">{{ $t("明亮清晰(像素高),人物半身照手持证件,请一边手持证件,另一边手持白纸日期(需要写下当天年月日在纸上)") }}</p>
				<img class="container_card_identity_img mb-1" src="@/image/personalCenter/setting/realName/verified10.png" alt="">
				<div class="container_card_icon_content padding-0 mb-1 pr-1 pl-1 br-8">
					<div class="upload_box" @click.stop="uploadClick">
							<div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
									<van-circle
											v-model="uploadProgress"
											:stroke-width="60"
											layer-color="#2e2e2e"
											:rate="uploadProgress"
											:speed="100"
											:text="uploadProgress + '%'"
									/>
							</div>
							<img v-if="uploadedImage" :src="uploadedImage" class="preview-image" alt="">
							<van-icon 
									v-if="uploadedImage"
									name="clear" 
									class="delete-icon"
									@click.stop="handleDelete"
							/>
							<template v-else-if="uploading">
								<div class="uploading_text">{{ $t("上传中...") }}</div>
							</template>
							<template v-else>
									<img src="@/image/personalCenter/setting/realName/carma.png" class="mb-0" alt="">
									<div class="upload_box_title">{{ $t("点击上传照片") }}</div>
							</template>
					</div>
				</div>
			</div>
			<div class="container_card_tax" v-else-if="type == 4">
				<div class="container_card_title mb-0">{{ $t("我们接受") }}</div>
				<div class="container_card_icon_content padding-0 mb-1 pr-1 pl-1 br-8">
					<div class="container_card_icon_content_item" v-for="(item,index) in identityList" :key="index">
						<div class="item_icon_box">
							<div class="item_icon"></div>
						</div>
						<div>{{ item }}</div>
					</div>
				</div>
				<div class="container_card_icon_content padding-0 mb-1 pr-1 pl-1 br-8">
					<div class="upload_box" @click.stop="uploadClicks">
							<div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
									<van-circle
											v-model="uploadProgress"
											:stroke-width="60"
											layer-color="#2e2e2e"
											:rate="uploadProgress"
											:speed="100"
											:text="uploadProgress + '%'"
									/>
							</div>
							<div v-if="uploadedFiles.length > 0" class="uploaded-files">
									<div v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
											<span class="file-name">{{ file.name }}</span>
											<span class="status-icon">✅</span>
											<span class="upload-time">{{ file.uploadTime }}</span>
									</div>
							</div>
							<van-icon 
									v-if="uploadedImage"
									name="clear" 
									class="delete-icon"
									@click.stop="handleDelete"
							/>
							<template v-else-if="uploading">
								<div class="uploading_text">{{ $t("上传中...") }}</div>
							</template>
							<template v-else>
									<img src="@/image/personalCenter/setting/realName/upload.png" class="mb-0" alt="">
									<div class="upload_box_title">{{ $t("点击上传") }}</div>
							</template>
					</div>
				</div>
			</div>
			<button @click="submit">{{ $t("提交") }}</button>
		</div>
		<input 
				type="file" 
				ref="fileInput" 
				hidden
				@change="handleFileUpload"
				accept="image/*,application/pdf"
		>
		<input 
				type="file" 
				ref="fileInputs" 
				hidden
				@change="handleFileUploads"
		>
  </div>
</template>

<script>
import { getRealName , changeMobile , uploadFile , uploadRealName , uploadUserInfo } from '@/request/personalCenter';
export default {
    name: 'PersonalSettingAuthentication',
	data(){
		return{
			type: 1,//认证类型
			id: 1,//用户ID
			uploadStatus: '', // 新增上传状态
			selectedFile: null, // 存储选中的文件
			uploadProgress: 0,  // 上传进度，暂时不好使
			uploading: false, // 上传状态
			uploadedImage: null, // 服务器返回的图片地址
			uploadedFiles: [], // 存储上传成功的文件信息
			uploadStatus: '',
			phoneNum: {
				nation: '中华人民共和国',
				phoneNumber: '',
				flag: require("@/image/personalCenter/setting/realName/country (243).png"),
				areaCode: '+086',
			},
			livingBills_icon_list:[
				this.$t("银行对账单"),
				this.$t("水电费(您提供的文件不应超过3个月互联网/有线电视/家及电话线路账单)"),
				this.$t("报税表"),
				this.$t("政府颁发的居住证明等"),
			],
			identityList:[
				this.$t("税号支持文件"),
				this.$t("企业成立证书或注册证明"),
				this.$t("受益所有权证明"),
				this.$t("官方政府签发的附有照片的身份证件"),
			],
			livingBills_list:[
				this.$t("屏幕截图、移动电话账单、医药费、购货收据保险报表")
			]
		}
	},
	mounted(){
		// 区分认证类型
		if(this.$route.params.type){
			this.type = this.$route.params.type;
			this.id = this.$route.params.id;
		}else{
			// 避免页面刷新，丢失类型，后期可做加密处理
			this.type = sessionStorage.getItem('personalSettingRealName');
			this.id = sessionStorage.getItem('personalSettingName');
		}
		if(sessionStorage.getItem('country')){
			let arr = JSON.parse(sessionStorage.getItem('country'))
			this.phoneNum = {
				...this.phoneNum,
				nation : arr.name_zh,
				flag : require(`@/image/nationalFlagImg/${arr.short_lower}.png`),
				areaCode: arr.tel,
			}
			sessionStorage.removeItem('country')
		}
		this.getInfo()
	},
	methods:{
		getInfo(){
			// type 1:身份证 2:生活账单 3:税务
			getRealName({type:1}).then(res=>{
				console.log(res)
			})
		},
		validatePhoneNumber(phoneNumber, countryCode) {
			// 移除所有非数字字符
			const cleanedNumber = phoneNumber.replace(/\D/g, '');
			console.log(countryCode)
			// 常见国家/地区手机号验证规则
			const phonePatterns = {
				'086': /^1[3-9]\d{9}$/, // 中国大陆
				'1': /^\d{10}$/, // 美国/加拿大
				'44': /^7\d{9}$/, // 英国
				'81': /^[789]\d{9}$/, // 日本
				'82': /^1\d{9,10}$/, // 韩国
				'852': /^[569]\d{7}$/, // 香港
				'853': /^6\d{7}$/, // 澳门
				'886': /^9\d{8}$/, // 台湾
				'65': /^[89]\d{7}$/, // 新加坡
				'60': /^1\d{8,9}$/, // 马来西亚
				'33': /^[67]\d{8}$/, // 法国
				'49': /^1[567]\d{9}$/, // 德国
				'7': /^[3489]\d{9}$/, // 俄罗斯
				'91': /^[6789]\d{9}$/, // 印度
				'61': /^4\d{8}$/, // 澳大利亚
				// 可以继续添加更多国家/地区的规则
			};
			
			// 获取国家代码(去掉+号)
			const code = countryCode.replace('+', '');
			
			// 如果有特定国家的验证规则，使用它
			if (phonePatterns[code]) {
				return phonePatterns[code].test(cleanedNumber);
			}
			
			// 默认国际手机号验证(6-15位数字)
			return /^\d{6,15}$/.test(cleanedNumber);
		},
		submit(){
			// 在这里需要判断type类型，然后走同的提交接口
			console.log(this.type)
			let obj = {
				type: this.type -1 ,
				images: this.uploadedImage
			}
			if(this.type == 1){
				// 修改手机号
				if(!this.phoneNum.phoneNumber || !this.validatePhoneNumber(this.phoneNum.phoneNumber, this.phoneNum.areaCode)){
					this.$toast.fail(this.$t("请输入正确的手机号"));
					return;
				}
				uploadUserInfo({mobile: this.phoneNum.phoneNumber , country:this.phoneNum.areaCode}).then(res=>{
					if(res.code == 1){
						this.$toast.success(res.msg);
						this.$router.go(-1);
					}else{
						this.$toast.fail(res.msg);
					}
				})
			}else if(this.type ==2 || this.type ==3 || this.type == 4){
				if(this.uploadedImage == null){
					this.$toast.fail(this.$t("未完成图片上传"));
					return;
				}
				// 生活账单
				uploadRealName(obj).then(res=>{
					if(res.code == 1){
						this.$toast.success(res.msg);
						this.$router.go(-1);
					}else{
						this.$toast.fail(res.msg);
					}
				})
			}
		},
		uploadClick(){
			if(this.uploading || this.uploadedImage) return; // 如果正在上传或已上传，则不允许再次点击
			this.$refs.fileInput.click() 
		},
		uploadClicks(){
			if(this.uploading || this.uploadedImage) return; // 如果正在上传或已上传，则不允许再次点击
			this.$refs.fileInputs.click() 
		},
		// 修改上传方法
		async handleFileUpload(e) {
			const file = e.target.files[0];
			if (!file) return;
			
			// 模拟上传进度
			const interval = setInterval(() => {
				this.uploadProgress = Math.min(this.uploadProgress + 10, 90);
			}, 200);

			try {
					const formData = new FormData();
					formData.append('file', file);
					
					// const response = await axios.post('/api/upload', formData, {
					// 		onUploadProgress: progressEvent => {
					// 				this.uploadProgress = Math.round(
					// 						(progressEvent.loaded * 100) / progressEvent.total
					// 				);
					// 		}
					// });

					clearInterval(interval);

					this.uploading = true; // 设置上传状态为进行中
					
					uploadFile({file: file}).then(res=>{
						if(res.code == 1){
							this.uploadProgress = 100;
							this.$toast.success(this.$t('上传成功'));
							this.uploadedImage = res.data;
							this.uploadStatus = 'uploaded';
						}else{
							this.$toast.fail(res.msg);
						}

						this.uploading = false; // 上传完成后重置状态
					})
					// this.uploadedImage = response.data.url; // 使用服务器返回的地址
					setTimeout(() => this.uploadProgress = 0, 1000);

			} catch (error) {
					this.$toast.fail('上传失败');
					this.uploadedImage = null;
					this.uploadProgress = 0;
					this.uploading = false; // 上传失败后重置状态
			}
		},
		async handleFileUploads(e) {
			// ...原有验证逻辑...
			const file = e.target.files[0];
			if (!file) return;
			console.log(e.target.files[0])
			// 生成预览
			this.uploadedImage = URL.createObjectURL(file);
			
			// 模拟上传进度
			const interval = setInterval(() => {
					this.uploadProgress = Math.min(this.uploadProgress + 10, 90);
			}, 200);
			try {
				const formData = new FormData();
				formData.append('file', file);
				// const response = await axios.post('/api/upload', formData);
				uploadFile({file: file}).then(res=>{
					if(res.code == 1){
						this.uploadProgress = 100;
						this.$toast.success(this.$t('上传成功'));
						this.uploadedImage = res.data;
						this.uploadStatus = 'uploaded';
						this.uploadedFiles = [{
							name: file.name,
							url: res.data.url,
							uploadTime: new Date().toLocaleString()
						}];
					}else{
						this.$toast.fail(res.msg);
					}
				})
				// this.$toast.success(this.$t('上传成功'));
				
				// 同时更新全局认证状态（示例）
				if(this.type === 2) {
					this.$store.commit('updateCertStatus', { 
						type: 'livingBills',
						status: 'pending_review' 
					});
				}
				clearInterval(interval);
				setTimeout(() => this.uploadProgress = 0, 1000);

			} catch (error) {
				this.$toast.fail(this.$t('上传失败'));
			}
		},
		handleDelete() {
			this.uploadedImage = null;
			this.uploadProgress = 0;
			this.selectedFile = null;
			// 清除input的值
			if(this.$refs.fileInput) {
				this.$refs.fileInput.value = '';
			}
		},
		goNationalIndexBar(){
			if(this.$route.name != 'NationalIndexBar'){
					this.$router.replace({
						name: 'NationalIndexBar',
					})
				}
		}
	}
}
</script>

<style>

</style>